package com.gs.m_home.fragment

import android.app.Dialog
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Handler.Callback
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.integration.android.IntentResult
import com.gs.common.API
import com.gs.common.constant.ActionConst
import com.gs.common.data.CartData
import com.gs.common.global.GlobalVariables
import com.gs.common.util.DialogUtil
import com.gs.common.util.QRCodeUtil
import com.gs.common.util.ToastUtil
import com.gs.m_home.R
import com.gs.m_home.adapter.CartAdapter
import com.gs.m_home.callback.OnDoAddGoodSoldCountStateCallback
import com.gs.m_home.callback.OnDoDeleteGoodStateCallback
import com.gs.m_home.callback.OnDoPayOrderStateCallback
import com.gs.m_home.callback.OnDoSubtractGoodSoldCountStateCallback
import com.gs.m_home.callback.OnDoUpdateCartGoodDataStateCallback
import com.gs.m_home.callback.OnGetCartOrderIdStateCallback
import com.gs.m_home.persistent.CartPersistent

class CartFragment : Fragment() {

    private val cartPersistent by lazy { CartPersistent.getInstance(requireContext()) }
    private val mCartDataList = ArrayList<CartData>()
    private lateinit var loadingTv: TextView
    private lateinit var emptyCartTv: TextView
    private lateinit var cart: RecyclerView
    private lateinit var cartTotalTv: TextView
    private lateinit var payBtn: Button
    private var orderTotalMoney: Double = 0.0
    private lateinit var mLoadingDialog: Dialog
    private var mQRCodeBitmap: Bitmap? = null

    private val handler = Handler(){
        when(it.what) {
            SHOW_LOADING_DIALOG_MSG -> {
                mLoadingDialog.show()
                true
            }
            DISMISS_LOADING_DIALOG_MSG -> {
                mLoadingDialog.dismiss()
                true
            }
            SHOW_QR_CODE_DIALOG_MSG -> {
                if (mQRCodeBitmap != null) {
                    val qrCodeDialog = DialogUtil.createQRCodeDialog(requireContext(), mQRCodeBitmap!!)
                    qrCodeDialog.setOnDismissListener {
                        updateCartGoodData()
                    }
                    qrCodeDialog.show()
                }
                true
            }
            else -> {
                false
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLoadingDialog = DialogUtil.createLoadingDialog(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.cart_fragment, container, false)

        loadingTv = view.findViewById(R.id.loading_tv)
        emptyCartTv = view.findViewById(R.id.empty_cart_tv)
        cart = view.findViewById<RecyclerView>(R.id.cart)
        cartTotalTv = view.findViewById(R.id.cart_total)
        payBtn = view.findViewById(R.id.pay_btn)

        // 显示加载数据中, 不显示cart
        loadingTv.visibility = View.VISIBLE
        emptyCartTv.visibility = View.GONE
        cart.visibility = View.GONE

        return view
    }

    override fun onResume() {
        super.onResume()
        // 配置 cart recyclerView
        val layoutManager = LinearLayoutManager(requireContext())
        cart.layoutManager = layoutManager
        val adapter = CartAdapter(requireContext(), mCartDataList)
        cart.adapter = adapter

        // 显示cart，不显示加载数据中
        loadingTv.visibility = View.GONE
        updateCartGoodData()
        cart.visibility = View.VISIBLE
        adapter.setCartItemAddCountBtnClickListener(object : CartAdapter.OnCartItemAddCountBtnClickListener{
            override fun onClick(position: Int, orderId: Int, goodId: Int) {
                cartPersistent.addGoodSoldCount(orderId, goodId, object : OnDoAddGoodSoldCountStateCallback{
                    override fun onAddGoodSoldCountSuccess() {
                        updateCartGoodData()
                    }

                    override fun onAddGoodSoldCountFailed() {
                        ToastUtil.showShortToast(requireContext(), "数量增加失败")
                    }
                })
            }
        })
        adapter.setCartItemSubtractCountBtnClickListener(object : CartAdapter.OnCartItemSubtractCountBtnClickListener{
            override fun onClick(position: Int, orderId: Int, goodId: Int) {
                cartPersistent.subtractGoodSoldCount(orderId, goodId, object : OnDoSubtractGoodSoldCountStateCallback{
                    override fun onSubtractGoodSoldCountSuccess() {
                        updateCartGoodData()
                    }

                    override fun onSubtractGoodSoldCountFailed() {
                        ToastUtil.showShortToast(requireContext(), "数量减少失败")
                    }
                })
            }
        })
        adapter.setCartItemDeleteBtnClickListener(object : CartAdapter.OnCartItemDeleteBtnClickListener{
            override fun onClick(position: Int, orderId: Int, goodId: Int) {
                val alertDialog = DialogUtil.createCommonAlertDialog(requireContext(), "删除", "这个商品") {
                    if (it == DialogUtil.CONFIRM_TO_DO) {
                        cartPersistent.deleteGood(orderId, goodId, object : OnDoDeleteGoodStateCallback{
                            override fun onDeleteGoodSuccess() {
                                ToastUtil.showShortToast(requireContext(), "删除成功")
                                updateCartGoodData()
                            }

                            override fun onDeleteGoodFailed() {
                                ToastUtil.showShortToast(requireContext(), "删除失败")
                            }
                        })
                    }
                }
                alertDialog.show()
            }
        })
        adapter.setCartItemLeftLayoutClickListener(object : CartAdapter.OnCartItemLeftLayoutClickListener{
            override fun onClick(position: Int, orderId: Int, goodId: Int) {
                val goods = GlobalVariables.goodsList
                if (goods == null){
                    ToastUtil.showShortToast(requireContext(), "跳转商品失败")
                    return
                }
                var pos = -1
                for ((index, good) in goods.withIndex()) {
                    if (good.id == goodId){
                        pos = index
                        break
                    }
                }
                val intent = Intent().apply {
                    action = ActionConst.TO_GOODS_DETAIL_ACTIVITY_ACTION
                    removeExtra("position")
                    putExtra("position", pos)
                }
                startActivity(intent)
            }
        })

        payBtn.setOnClickListener {
            val cartDataList = GlobalVariables.cartDataList
            if (cartDataList.isNullOrEmpty()) return@setOnClickListener
            val loginUser = GlobalVariables.loginUser
            if (loginUser == null) {
                ToastUtil.showShortToast(requireContext(), "支付失败")
                return@setOnClickListener
            }
            // 获取购物车order id
            cartPersistent.getCartOrderId(loginUser.userName, object : OnGetCartOrderIdStateCallback{
                override fun onGetCartOrderIdSuccess() {
                    val orderId = GlobalVariables.curCartOrderId
                    if (orderId <= -1) {
                        ToastUtil.showShortToast(requireContext(), "获取购物车订单编号失败")
                        return
                    }
                    Thread{
                        handler.sendEmptyMessage(SHOW_LOADING_DIALOG_MSG)
                        mQRCodeBitmap = QRCodeUtil.generateQRCode(resources, "http://${API.IP}:${API.PORT}/api/cart/pay?username=${GlobalVariables.loginUser?.userName}&orderId=${orderId}&token=${GlobalVariables.token}", 500, 500)
                        handler.sendEmptyMessage(DISMISS_LOADING_DIALOG_MSG)
                        handler.sendEmptyMessage(SHOW_QR_CODE_DIALOG_MSG)
                    }.start()
                }

                override fun onGetCartOrderIdFailed() {
                    ToastUtil.showShortToast(requireContext(), "获取购物车订单编号失败")
                }

            })

//            cartPersistent.payOrder(loginUser.userName,object : OnDoPayOrderStateCallback{
//                override fun onPayOrderSuccess() {
//                    updateCartGoodData()
//                    ToastUtil.showShortToast(requireContext(), "支付成功")
//                }
//
//                override fun onPayOrderFailed() {
//                    ToastUtil.showShortToast(requireContext(), "支付失败")
//                }
//
//                override fun onNetworkError() {
//                    ToastUtil.showShortToast(requireContext(), "无法连接网络！")
//                }
//
//                override fun onServerError() {
//                    ToastUtil.showShortToast(requireContext(), "无法连接服务器！")
//                }
//            })
        }
    }

    private fun updateCartGoodData() {
        val loginUser = GlobalVariables.loginUser
        if (loginUser == null) {
            ToastUtil.showShortToast(requireContext(), "购物车数据更新失败")
            return
        }
        orderTotalMoney = 0.0
        mCartDataList.clear()
        cartPersistent.updateCartGoodData(loginUser.userName, object : OnDoUpdateCartGoodDataStateCallback{
            override fun onUpdateCartGoodDataSuccess() {
                val cartDataList = GlobalVariables.cartDataList
                if (cartDataList == null) {
                    ToastUtil.showShortToast(requireContext(), "购物车数据更新失败！")
                    return
                }
                if (cartDataList.isEmpty()) {
                    emptyCartTv.visibility = View.VISIBLE
                } else {
                    emptyCartTv.visibility = View.GONE
                }
                for (cartData in cartDataList) {
                    orderTotalMoney += cartData.goodTotalMoney
                    mCartDataList.add(cartData)
                }
                cart.adapter?.notifyDataSetChanged()
                cartTotalTv.text = orderTotalMoney.toString()
            }

            override fun onUpdateCartGoodDataFailed() {
                ToastUtil.showShortToast(requireContext(), "购物车数据更新失败")
            }

            override fun onNetworkError() {
                ToastUtil.showShortToast(requireContext(), "无法连接网络！")
            }

            override fun onServerError() {
                ToastUtil.showShortToast(requireContext(), "无法连接服务器！")
            }
        })
    }

    companion object{
        const val SHOW_LOADING_DIALOG_MSG = 110
        const val DISMISS_LOADING_DIALOG_MSG = 111
        const val SHOW_QR_CODE_DIALOG_MSG = 112
    }
}